<template>
  <div class="serviceView">
    <!-- 标题 -->
    <Title>
      <template #default>{{ title }}</template>
    </Title>
    <!-- 内容区 -->
    <section class="contentLayout">
      <div class="service">
        <div style="display: flex;justify-content: right;align-items:center; vertical-align: center;">
          <el-button icon="Plus" type="primary" @click="openFormVisible('新建',false)" style="margin-right: 5px">新建</el-button>
          <div class="tableSet1">
            <div>
              <el-tooltip  effect="dark" content="刷新" placement="top">
                <el-button :type="'text'" @click="Refresh"><el-icon size="19" style="color: #1F1F1F"><RefreshRight/></el-icon></el-button>
              </el-tooltip>
            </div>
            <div>
              <el-tooltip  effect="dark" content="密度" placement="top">
                <el-dropdown placement="bottom-start" trigger="click" size='large'>
                  <el-button type="text"><el-icon size="18" style="color: #1F1F1F"><Sort/></el-icon></el-button>
                  <template #dropdown>
                    <el-dropdown-menu >
                      <el-dropdown-item
                          @click="changeSize('默认')"
                          :style="{backgroundColor:active===true ?'#E6F7FF' : ''}">
                        默认
                      </el-dropdown-item>
                      <el-dropdown-item
                          @click="changeSize('中等')"
                          :style="{backgroundColor:active===true ?'#E6F7FF' : ''}">
                        中等
                      </el-dropdown-item>
                      <el-dropdown-item
                          @click="changeSize('紧凑')"
                          :style="{backgroundColor:active===true ?'#E6F7FF' : ''}">
                        紧凑
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-tooltip>
            </div>
            <div>
              <el-icon size="19"><Setting /></el-icon>
            </div>
          </div>
        </div>
        <el-table :data="servicelist.list" style="width: 100%" :size="tableSize" v-loading="loading">
          <el-table-column label="序号" width="80" type="index" />
          <el-table-column prop="question" label="问题" width="200" show-overflow-tooltip></el-table-column>
          <el-table-column prop="answer" label="答案" width="300" show-overflow-tooltip></el-table-column>
          <el-table-column prop="enable_status" label="是否启用" width="330">
            <template #default="{ row }">
              <el-button v-if="row.enable_status === 1" class="btn-on" size="small">启用</el-button>
              <el-button v-if="row.enable_status === 0" class="btn-off" size="small">禁用</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="推荐值" width="300"></el-table-column>
          <el-table-column fixed="right" label="操作" min-width="100">
            <template #default="{row}">
              <span @click="openFormVisible('编辑',row)" class="Edit">编辑</span>
              <span @click="handleDelete(row)" class="Delete">删除</span>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <div style="display: flex;justify-content: right;padding: 10px">
          <div class="pageText" style="float: left;margin: 5px 15px">
            第 {{ (AllPages.page - 1) * AllPages.per_page + 1 }} -
            <span v-if="AllPages.per_page*AllPages.page<=servicelist.total">{{AllPages.page*AllPages.per_page}}</span>
            <span v-else>{{servicelist.total}}</span>
            条 / 总共 {{ servicelist.total }} 条
          </div>
          <el-pagination
              :current-page="AllPages.page"
              :page-size="AllPages.per_page"
              :pager-count="3"
              background
              layout="prev, pager, next"
              :total="AllPages.total"
              size="small"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              style="margin-top: 3px"
          />
        </div>
      </div>
    </section>

    <!-- 弹窗 -->
    <el-dialog
        class="dialogFormVisible"
        v-model="dialogFormVisible"
        :title="dialogTitle"
        width="640"
        :before-close="handleClose">
      <el-form :model="addServiceStore" ref="FormRef" :rules="rules" label-position="top" :label-width="formLabelWidth " >
        <el-form-item prop="question" label="问题详情">
          <el-input
              v-model="addServiceStore.question"
              :autosize="{ minRows: 3,maxRows:10}"
              autocomplete="off"
              clearable
              style="width: 605px"
              type="textarea"
              placeholder="请输入问题详情"
          />
        </el-form-item>
        <el-form-item prop="answer" label="答案详情">
          <el-input
              v-model="addServiceStore.answer"
              :autosize="{ minRows: 3,maxRows:10}"
              autocomplete="off"
              clearable
              style="width: 605px"
              type="textarea"
              placeholder="请输入答案详情"
          />
        </el-form-item>
        <el-form-item class="inputWidth" prop="enable_status" label="是否启用" >
          <el-select
              v-model="addServiceStore.enable_status"
              placeholder="请选择是否启用"
              clearable
          >
            <el-option label="禁用" :value="0" />
            <el-option label="启用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item class="inputWidth" prop="weight" label="推荐值(0为未推荐)" >
          <el-input-number
              v-model="addServiceStore.weight"
              class="mx-4"
              :min="0"
              controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer style="border-bottom: 1px solid #f0f0f0">
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button v-if="dialogTitle==='添加'" type="primary" @click="submitForm(FormRef,'新建')">
            确定
          </el-button>
          <el-button v-if="dialogTitle==='编辑'" type="primary" @click="submitForm(FormRef,'编辑')">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>

</template>
<script setup>
import Title from "@/components/public/Title.vue";
import { useRoute } from "vue-router";
import {ref, reactive} from "vue";
import {ServiceList, ServiceDelete, ServiceUpdate, ServiceStore} from "@/network/service";
import {Plus, RefreshRight, Setting, Sort} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox } from "element-plus";

const route = useRoute();
const title = route.meta.title;

const servicelist =ref({
  list:[],
  total:0,
})
const AllPages=reactive({
  page:1,
  per_page:10,
  total:0
})
const loading= ref(true)

const getServiceList=()=>{
  ServiceList(AllPages).then((res)=>{
    console.log(res.data.data)
    const {list}=res.data.data
    servicelist.value.list=list
    servicelist.value.total=list.length
    AllPages.total=res.data.length
    if (res.data.code===0){
      setTimeout(()=>{
        loading.value=false
      },600)
    }else {
      loading.value=true
    }
  })
}
getServiceList()

const addServiceStore=ref({
  question:'',
  answer:'',
  enable_status:1,
  weight:0
})
const checkService ={...addServiceStore.value}
const FormRef=ref()
//表单校验规则
const rules=reactive({
  question:[{required: true, trigger: 'change',message: '请输入问题详情'}],
  answer:[{required: true, trigger: 'change',message: '请输入答案详情'}],
  enable_status:[{ required: true, trigger: 'change',message: '请选择账号状态'}],
  weight:[{required: true, trigger: 'change',message: "请设置推荐值"}],
})

// 控制弹窗显示
const dialogFormVisible=ref(false)
// 弹窗标题
const dialogTitle=ref('')
//表单行宽
const formLabelWidth = '140px'
//当为编辑时对数据储存
const selectedRow=ref()

// 弹窗
const openFormVisible=(type,row)=>{
  dialogFormVisible.value=true
  if (type==='新建'){
    dialogTitle.value='添加'
    if (FormRef.value){
      addServiceStore.value=checkService
      FormRef.value.resetFields();
    }
  }else if (type==='编辑'){
    dialogTitle.value='编辑'
    //记录当前行数据
    selectedRow.value=row
    //将选中行数据赋值给addBoss
    addServiceStore.value={...row}
    //对后端获取的一些数据字段进行判断
  }
}

//提交表单数据
const submitForm = async (formEl,type) => {
  if (type==='新建'){
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        ServiceStore(addServiceStore.value).then((data)=>{
          if (data.data.code ===0) {
            dialogFormVisible.value = false;
            getServiceList()
            ElMessage({
              showClose: true,
              message: "添加成功",
              type: "success",
            });
          }else {
            dialogFormVisible.value = false;
            ElMessage({
              showClose: true,
              message: "添加失败",
              type: "error",
            });
          }
          console.log(data,'dt')
        })
        // console.log('submit!',addBoss.value)
      } else {
        console.log('error submit!', fields)
      }
    })
  }else if (type==='编辑'){
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        const row= {...selectedRow.value}
        ServiceUpdate(row.id,{
          question:row.question,
          answer:row.answer,
          enable_status:row.enable_status,
          weight:row.weight,
        }).then((data)=>{
          if (data.data.code===0){
            dialogFormVisible.value = false;
            getServiceList()
            ElMessage({
              showClose: true,
              message: "编辑成功",
              type: "success",
            });
          }else {
            dialogFormVisible.value = false;
            ElMessage({
              showClose: true,
              message: data.data.message,
              type: "error",
            });
          }
          console.log(data,'updata')
        })

        getServiceList()
      } else {
        console.log('error submit!', fields)
      }
    })
  }
}

//弹窗右上角小x关闭并重置表单清除校验
const handleClose = () => {
  dialogFormVisible.value=false
}
//取消提交并重置表单清除校验
const cancel = () => {
  dialogFormVisible.value=false
}

//刷新
const Refresh= () => {
  loading.value=true
  getServiceList()
}




//密度
const tableSize = ref('default')
const active = ref([false, true, false])

const sizeMap = {
  '紧凑': ['small', [true, false, false]],
  '中等': ['default', [false, true, false]],
  '默认': ['large', [false, false, true]],
}

const changeSize = (size) => {
  const [newSize, newActive] = sizeMap[size] || sizeMap['中等']  // 默认值处理
  tableSize.value = newSize
  active.value = newActive
}
const handleCurrentChange = (val) => {
  AllPages.page=val
  loading.value=true
  getServiceList()
}
const handleSizeChange = (val) => {
  AllPages.per_page=val
  AllPages.page=1
  loading.value=true
  getServiceList()
}

</script>

<style lang="scss">
.service{
  background-color: white;
  padding: 0 24px;
}
.tableSet1 {
  padding: 10px 0;
  display: flex;
  justify-content: space-around;
  div {
    padding: 4px;
    display: flex;
    align-items: center;
    vertical-align: center;
  }
}
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.btn-on {
  color: #389e0d;
  background: #f6ffed;
  border-color: #b7eb8f;
}

.btn-off {
  color: #cf1322;
  background: #fff1f0;
  border-color: #ffa39e;
}
.Edit,.Delete{
  cursor: pointer;
  color:#1890ff;
  padding:0 5px ;
}
</style>